﻿#include "A-showhome.h"
#include <QMouseEvent>
#include <QTimer>

ShowHome::ShowHome(QWidget *parent) : QMainWindow(parent)
{
    if(!db.open_db()){
        exit(-1);
    }

    // 设置窗口标题
    setWindowTitle("馋了吗 - 外卖平台");

    // 设置UI界面
    setupUI(false);

    // 创建堆叠窗口部件，用于切换页面
    stackedWidget = new QStackedWidget(this);

    // 创建各个页面
    businessListPage = new BusinessListPage(db, this);
    productList = new UserProductList(db, this);
    orderPage = new OrderPage(db, this);
    userOrderPage = new UserOrderPage(db, this);
    adminPage = new AdminPage(db, this);
    adminWindow = new AdminWindow(db, this);
    profilePage = new ProfilePage(db, this);

    // 连接商户列表页面的信号
    connect(businessListPage, &BusinessListPage::businessSelected,
            this, &ShowHome::onBusinessSelected);

    // 连接商品列表页面的信号
    connect(productList, &UserProductList::backButtonClicked,
            this, &ShowHome::onBackToHomeClicked);
    
    // 连接商品列表页面的openProfilePage信号
    connect(productList, &UserProductList::openProfilePage,
            this, &ShowHome::onProfileActionTriggered);

    // 连接个人信息页面的信号
    connect(profilePage, &ProfilePage::nameChanged, [this](const QString &newName) {
        this->name = newName;
        // 可以在这里更新其他地方显示的用户名
    });
    connect(profilePage, &ProfilePage::profileUpdated, this, [this]() {
        if (businessListPage) businessListPage->refresh();
    });

    // 添加页面到堆叠窗口
    stackedWidget->addWidget(businessListPage);
    stackedWidget->addWidget(productList);
    stackedWidget->addWidget(orderPage);
    stackedWidget->addWidget(userOrderPage);
    stackedWidget->addWidget(adminPage);
    stackedWidget->addWidget(adminWindow);
    stackedWidget->addWidget(profilePage);

    // 设置中央窗口部件
    setCentralWidget(stackedWidget);

    // 创建状态栏
    QStatusBar *statusBar = new QStatusBar(this);
    setStatusBar(statusBar);

    // 创建状态栏按钮
    homeAction = new QAction("首页", this);
    orderAction = new QAction("订单", this);
    adminAction = new QAction("后台", this);
    profileAction = new QAction("个人信息", this);

    // 准备按钮样式
    QString normalStyle = "QToolButton { color: #333333; padding: 8px 16px; font-size: 14px; font-weight: bold; border: none; background: transparent; } "
                         "QToolButton:hover { color: #1890ff; }";
    QString activeStyle = "QToolButton { color: #1890ff; padding: 8px 16px; font-size: 14px; font-weight: bold; border: none; background: transparent; border-bottom: 2px solid #1890ff; }";

    // 连接状态栏按钮信号
    connect(homeAction, &QAction::triggered, this, &ShowHome::onHomeActionTriggered);
    connect(orderAction, &QAction::triggered, this, &ShowHome::onOrderActionTriggered);
    connect(adminAction, &QAction::triggered, this, &ShowHome::onAdminActionTriggered);
    connect(profileAction, &QAction::triggered, this, &ShowHome::onProfileActionTriggered);

    // 创建状态栏小部件
    QWidget *statusWidget = new QWidget(this);
    QHBoxLayout *statusLayout = new QHBoxLayout(statusWidget);
    statusLayout->setSpacing(0);
    statusLayout->setContentsMargins(0, 0, 0, 0);
    
    // 添加按钮到状态栏，按照固定顺序：首页、订单、后台、个人信息
    QToolButton *homeButton = new QToolButton(this);
    homeButton->setDefaultAction(homeAction);
    homeButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    homeButton->setStyleSheet(activeStyle);
    homeButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    QToolButton *orderButton = new QToolButton(this);
    orderButton->setDefaultAction(orderAction);
    orderButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    orderButton->setStyleSheet(normalStyle);
    orderButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    QToolButton *adminButton = new QToolButton(this);
    adminButton->setDefaultAction(adminAction);
    adminButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    adminButton->setStyleSheet(normalStyle);
    adminButton->setVisible(false); // 默认隐藏后台按钮
    adminButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    QToolButton *profileButton = new QToolButton(this);
    profileButton->setDefaultAction(profileAction);
    profileButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    profileButton->setStyleSheet(normalStyle);
    profileButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    
    // 按照固定顺序添加按钮
    statusLayout->addWidget(homeButton);
    statusLayout->addWidget(orderButton);
    statusLayout->addWidget(adminButton);
    statusLayout->addWidget(profileButton);

    statusBar->addPermanentWidget(statusWidget, 1);

    // 显示首页
    stackedWidget->setCurrentWidget(businessListPage);
}

//菜单栏
void ShowHome::setupUI(bool islogin){
    // 创建菜单栏
    QMenuBar *menuBar = new QMenuBar(this);

    // 创建右侧控件
    right_close = new QPushButton("退出", this);
    right_login = new QPushButton(islogin ? "个人信息" : "登录", this);
    searchBox = new QLineEdit(this);
    searchBox->setPlaceholderText("搜索商户...");
    searchBox->setFixedWidth(200);

    // 创建水平布局容纳右侧控件
    QWidget *rightWidget = new QWidget(this);
    QHBoxLayout *rightLayout = new QHBoxLayout(rightWidget);
    rightLayout->addWidget(searchBox);
    rightLayout->addWidget(right_login);
    rightLayout->addWidget(right_close);
    rightLayout->setContentsMargins(0, 0, 0, 0);

    // 将布局控件设置为菜单栏的corner widget
    menuBar->setCornerWidget(rightWidget, Qt::TopRightCorner);

    QMenu *fileMenu = menuBar->addMenu("文件(&F)");
    QAction *saveAction = fileMenu->addAction("保存设置");
    QAction *exitAction = fileMenu->addAction("退出");

    setMenuBar(menuBar);

    // 连接菜单动作
    connect(saveAction, &QAction::triggered, this, &QApplication::quit);
    connect(exitAction, &QAction::triggered, this, &QApplication::quit);
    connect(right_close, &QPushButton::clicked, this, &ShowHome::onLogoutClicked);
    connect(right_login, &QPushButton::clicked, this, &ShowHome::onLoginClicked);
}

void ShowHome::updateLoginStatus(bool loggedIn, const QString &username)
{
    isLogin = loggedIn;
    currentUser = username;
    if (!loggedIn) {
        userIdentity = -1;  // 退出登录时清除身份信息
        phone_id = -1;
        // 关闭商家后台窗口
        if(bm) {
            qDebug() << "退出登录时关闭商家后台窗口";
            bm->close();
            bm = nullptr;
        }
    }
    right_login->setText(loggedIn ? "个人信息" : "登录");
    
    // 查找所有状态栏按钮
    QToolButton *homeButton = nullptr;
    QToolButton *orderButton = nullptr;
    QToolButton *adminButton = nullptr;
    QToolButton *profileButton = nullptr;
    for (QToolButton *button : findChildren<QToolButton*>()) {
        if (button->defaultAction() == homeAction) {
            homeButton = button;
        } else if (button->defaultAction() == orderAction) {
            orderButton = button;
        } else if (button->defaultAction() == adminAction) {
            adminButton = button;
        } else if (button->defaultAction() == profileAction) {
            profileButton = button;
        }
    }
    
    if (loggedIn) {
        // 根据用户身份调整按钮显示
        bool isSpecialUser = (userIdentity == 0 || userIdentity == 2 || userIdentity == 3); // 管理员、商户或骑手
        
        // 特殊用户隐藏首页按钮，显示后台按钮
        if (homeButton) {
            homeButton->setVisible(!isSpecialUser);
        }
        
        // 只有普通用户显示订单按钮，其他用户隐藏
        if (orderButton) {
            orderButton->setVisible(userIdentity == 1);
        }
        
        if (adminButton) {
            adminButton->setVisible(isSpecialUser);
            // 根据身份设置后台按钮文本
            if (userIdentity == 0) {
                adminAction->setText("管理后台");
            } else if (userIdentity == 2) {
                adminAction->setText("商户后台");
            } else if (userIdentity == 3) {
                adminAction->setText("骑手后台");
            }
        }
        
        // 所有用户都显示个人信息按钮
        if (profileButton) {
            profileButton->setVisible(true);
        }
        
        // 登录后自动跳转到相应页面
        if (isSpecialUser) {
            // 特殊用户登录后直接跳转到个人信息页面
            QTimer::singleShot(100, this, &ShowHome::onProfileActionTriggered);
        }
    } else {
        // 未登录状态，显示首页，隐藏后台
        if (homeButton) {
            homeButton->setVisible(true);
        }
        if (orderButton) {
            orderButton->setVisible(true); // 未登录时也显示订单按钮，点击会提示登录
        }
        if (adminButton) {
            adminButton->setVisible(false);
        }
        
        // 显示首页
        stackedWidget->setCurrentWidget(businessListPage);
        updateStatusBarButtonStyles(0); // 0表示首页按钮
    }
}

void ShowHome::onLoginClicked() {
    if (!isLogin) {
        // 创建登录窗口
        LoginWindow *loginWindow = new LoginWindow(db, this);

        // 连接登录成功信号
        connect(loginWindow, &LoginWindow::loginSuccess,
                [this](bool loggedIn, const QString &username, int identity, int phoneId) {
            // 更新状态
            this->userIdentity = identity;
            this->phone_id = phoneId;
            this->currentUser = username;

            // 在下一个事件循环中获取用户名和显示欢迎信息，避免阻塞UI
            QTimer::singleShot(0, this, [this, username]() {
                this->getName();
                this->updateLoginStatus(true, username);
                QMessageBox::information(this, "登录成功", "欢迎，" + name + "！");
                
                // 如果当前显示的是个人信息页面，则设置用户信息
                if (stackedWidget->currentWidget() == profilePage) {
                    profilePage->setUserInfo(userIdentity, phone_id, name);
                }
            });
        });

        // 连接注册成功信号
        connect(loginWindow, &LoginWindow::registrationSuccess, this, [this]() {
            // 在注册成功后，延迟一段时间再打开登录窗口
            QTimer::singleShot(500, this, &ShowHome::onLoginClicked);
        });

        // 显示登录窗口
        loginWindow->setAttribute(Qt::WA_DeleteOnClose);
        loginWindow->setWindowModality(Qt::ApplicationModal); // 设置为模态窗口
        loginWindow->show();
        loginWindow->activateWindow(); // 确保窗口获得焦点
        loginWindow->raise(); // 确保窗口在最前面
    } else {
        // 已登录，切换到个人信息页面（与底部导航栏行为一致）
        profilePage->setUserInfo(userIdentity, phone_id, name);
        stackedWidget->setCurrentWidget(profilePage);
        updateStatusBarButtonStyles(3); // 3表示个人信息按钮
    }
}

void ShowHome::getName(){
    // 已登录，显示个人信息
    QString sql = "SELECT %1 FROM %2 where phone_id = %3";
    switch(userIdentity){
    case 0:
        sql = sql.arg("admin_name").arg("admin").arg(phone_id);
        identityName = "管理员";
        break;
    case 1:
        sql = sql.arg("user_name").arg("user").arg(phone_id);
        identityName = "普通用户";
        break;
    case 2:
        sql = sql.arg("business_name").arg("business").arg(phone_id);
        identityName = "商户";
        break;
    case 3:
        sql = sql.arg("rider_name").arg("rider").arg(phone_id);
        identityName = "骑手";
        break;
    default:
        QMessageBox :: information(this,"错误","异常身份");
        return;
    }
    // 尝试不同的查询方式
    qDebug()<<"showhome.cpp-240:"<<sql;
    query = db.exec(sql);
    query.next();
    name = query.value(0).toString();
    qDebug() << "查询结果: " << name;
}

void ShowHome::onLogoutClicked() {
    if (isLogin) {
        updateLoginStatus(false);
        
        // 如果当前在个人信息页面，则切换到首页
        if (stackedWidget->currentWidget() == profilePage) {
            stackedWidget->setCurrentWidget(businessListPage);
            updateStatusBarButtonStyles(0); // 0表示首页按钮
        }
        
        QMessageBox::information(this, "退出登录", "您已退出登录。");
    } else {
        QApplication::quit();
    }
}

void ShowHome::onBusinessSelected(int businessId, const QString &businessName) {
    // 加载商户商品页面
    qDebug()<<"打开商品列表-"<<phone_id;
    productList->setPhone_id(phone_id);
    productList->loadBusinessProducts(businessName, businessId);
    stackedWidget->setCurrentWidget(productList);
}
//（从商品列表）返回首页
void ShowHome::onBackToHomeClicked() {
    stackedWidget->setCurrentWidget(businessListPage);

    // 更新状态栏按钮样式
    updateStatusBarButtonStyles(0); // 0表示首页按钮
}
// 切换到首页
void ShowHome::onHomeActionTriggered() {
    stackedWidget->setCurrentWidget(businessListPage);

    // 更新状态栏按钮样式
    updateStatusBarButtonStyles(0);
}

void ShowHome::onOrderActionTriggered() {
    // 检查用户是否已登录
    if (!isLogin) {
        // 未登录，显示登录窗口
        onLoginClicked();
        return;
    }
    
    // 根据用户身份切换到不同的订单页面
    if (userIdentity == 1) { // 普通用户
        userOrderPage->setUserInfo(phone_id, userIdentity);
        stackedWidget->setCurrentWidget(userOrderPage);
    } else if (userIdentity == 3) { // 骑手用户
        // 骑手用户在点击"后台"时查看订单页面，这里不做处理
        QMessageBox::information(this, "提示", "骑手用户请点击‘后台’查看订单");
        return;
    } else {
        // 商户和管理员不显示订单页面
        QMessageBox::information(this, "提示", "您的账户类型无法查看此页面");
        return;
    }

    // 更新状态栏按钮样式
    updateStatusBarButtonStyles(1);
}

void ShowHome::onAdminActionTriggered() {
    // 切换到后台页面
    // 根据用户身份选择不同的后台界面
    if(userIdentity == 0) { // 管理员使用AdminWindow
        stackedWidget->setCurrentWidget(adminWindow);
    } else if(userIdentity == 3){ // 骑手使用OrderPage
        // 设置骑手订单页面的用户信息
        orderPage->setUserInfo(phone_id, userIdentity);
        stackedWidget->setCurrentWidget(orderPage);
    } else if(userIdentity == 2){
        // 商家后台管理
        qDebug() << "商家点击后台按钮，当前bm指针:" << (bm ? "非空" : "空");
        
        // 如果窗口已存在则激活，否则创建新窗口
        if(bm == nullptr) {
            // 获取商家信息
            QString sql = QString("SELECT business_id, business_name FROM business WHERE phone_id = %1").arg(phone_id);
            query = db.exec(sql);
            if(query.next()) {
                currentBusinessId = query.value(0).toInt();
                currentBusinessName = query.value(1).toString();

                bm = new Buss_main();
                bm->setBusiness1_id(currentBusinessId);
                bm->setBusiness1_name(currentBusinessName);

                // 连接窗口关闭信号
                connect(bm, &Buss_main::windowAboutToClose, this, [this]() {
                    qDebug() << "收到商家后台窗口即将关闭信号";
                });
                
                connect(bm, &Buss_main::destroyed, this, [this]() {
                    bm = nullptr; // 窗口关闭后重置指针
                    qDebug() << "商家后台窗口已关闭，指针已重置";
                });

                bm->show();
                qDebug() << "创建新的商家后台窗口，商家ID:" << currentBusinessId << "商家名称:" << currentBusinessName;
            } else {
                QMessageBox::warning(this, "错误", "未能获取商家信息");
                qDebug() << "无法获取商家信息，phone_id:" << phone_id;
            }
        } else {
            // 检查窗口是否真的还存在（可能被隐藏了）
            if (bm->isVisible()) {
                // 窗口可见，激活并置顶
                bm->activateWindow();
                bm->raise();
                qDebug() << "激活现有商家后台窗口";
            } else {
                // 窗口被隐藏了，重新显示
                bm->show();
                bm->activateWindow();
                bm->raise();
                qDebug() << "重新显示隐藏的商家后台窗口";
            }
        }
    }

    // 更新状态栏按钮样式
    updateStatusBarButtonStyles(2);
}

void ShowHome::onProfileActionTriggered() {
    // 检查用户是否已登录
    if (!isLogin) {
        // 未登录，显示登录窗口
        onLoginClicked();
        return;
    }
    
    // 已登录，设置用户信息并切换到个人信息页面
    profilePage->setUserInfo(userIdentity, phone_id, name);
    stackedWidget->setCurrentWidget(profilePage);

    // 更新状态栏按钮样式
    updateStatusBarButtonStyles(3);
    
    // 连接昵称变更信号
    connect(profilePage, &ProfilePage::nameChanged, [this](const QString &newName) {
        this->name = newName;
        // 可以在这里更新其他地方显示的用户名
    }); // 使用UniqueConnection避免重复连接
}

// 辅助函数：更新状态栏按钮样式
void ShowHome::updateStatusBarButtonStyles(int activeIndex) {
    // 准备样式
    QString normalStyle = "QToolButton { color: #333333; padding: 8px 16px; font-size: 14px; font-weight: bold; border: none; background: transparent; } "
                         "QToolButton:hover { color: #1890ff; }";
    QString activeStyle = "QToolButton { color: #1890ff; padding: 8px 16px; font-size: 14px; font-weight: bold; border: none; background: transparent; border-bottom: 2px solid #1890ff; }";
    
    // 直接查找对应的按钮并设置样式
    QToolButton *homeButton = nullptr;
    QToolButton *orderButton = nullptr;
    QToolButton *adminButton = nullptr;
    QToolButton *profileButton = nullptr;
    
    // 查找所有按钮
    for (QToolButton *button : findChildren<QToolButton*>()) {
        if (button->defaultAction() == homeAction) {
            homeButton = button;
        } else if (button->defaultAction() == orderAction) {
            orderButton = button;
        } else if (button->defaultAction() == adminAction) {
            adminButton = button;
        } else if (button->defaultAction() == profileAction) {
            profileButton = button;
        }
    }
    
    // 重置所有可见按钮的样式
    if (homeButton && homeButton->isVisible()) {
        homeButton->setStyleSheet(normalStyle);
    }
    if (orderButton && orderButton->isVisible()) {
        orderButton->setStyleSheet(normalStyle);
    }
    if (adminButton && adminButton->isVisible()) {
        adminButton->setStyleSheet(normalStyle);
    }
    if (profileButton && profileButton->isVisible()) {
        profileButton->setStyleSheet(normalStyle);
    }
    
    // 根据activeIndex设置活动按钮样式
    switch (activeIndex) {
    case 0: // 首页
        if (homeButton && homeButton->isVisible()) {
            homeButton->setStyleSheet(activeStyle);
        }
        break;
    case 1: // 订单
        if (orderButton && orderButton->isVisible()) {
            orderButton->setStyleSheet(activeStyle);
        }
        break;
    case 2: // 后台
        if (adminButton && adminButton->isVisible()) {
            adminButton->setStyleSheet(activeStyle);
        }
        break;
    case 3: // 个人信息
        if (profileButton && profileButton->isVisible()) {
            profileButton->setStyleSheet(activeStyle);
        }
        break;
    }
}

ShowHome::~ShowHome()
{
    db.close();
}
